package com.share.example.bcs.server.server.protocol.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
        Channel channel = ctx.channel();

        //1.读取数据
        String content = httpRequest.content().toString();
        String ip = channel.remoteAddress().toString();
        log.info("reciveMsg ip={},lenth={},content={}", ip, content.length(), content);

        //2.定义输出数
        String data = "{\"aa\":\"我收到了你的信息\"}";

        //3.输出数据
        ByteBuf sendData = Unpooled.copiedBuffer(data, CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, sendData);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        channel.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

        //ChannelInboundHandlerAdapter.channelRead(ChannelHandlerContext ctx, Object msg)方并不会报错
        //原因是并未检验ByteBuf的计数器,而SimpleChannelInboundHandler需要收到
        httpRequest.retain();

        //5.释放请求
        httpRequest.release();
        ctx.close();
    }
}
